options
Files Sandbox Timm Mar10 Revised

Read Command-Line Options

Problem
=======

Suppose a script uses command-line arguments with flags like _-a_ or,
if an argument is to be set _-x ARG_. If so, then something
has to read those flags, then remove them so that Awk can run
the remaining arguments, as per usual.

Solution
========

The _option_ function revises the two magic Awk variables _ARGC_ (the
number of arguments) and _ARGV_ (the values of those arguments). In
the revised version, all the flags are removed and _ARGC_ is set to a
smaller number (the number of arguments without the flags).  

The following example calls shows _ARGC_ being changed directly. Note that
_ARGV_ is changed inside the function call.  In this example, we
defined flags _-a_, _c_, and _h_. The _-a_ variable is given a default
value (via the syntax _a=1_). The _options_ function assumes that any
flag with an existing value expects a command line argument. So, in
this example, this command line is legal:

  -c -a 21 -h

but this command line flags an error (because there is no argument given to _-a_:

  -c -a -h

Example
-------

 function optionsDemo(opt) { # returns 0 if bad options
      s2a("a=1;c=;h=",opt,"[=;]")
      ARGC = options(opt,ARGV,ARGC)
 }

Code
----

 function options(opt,input,n,  key,i,j,k,tmp) {
   for(i=1;i<=n;i++)  { # explore argstill no more flags
      key = input[i];
      if (sub(/^[-]+/,"",key))  { # we have a new flag
	 if (key in opt)         # if legal flag, change its value
	     opt[key] = (no("a" opt[key])) ? 1 : input[++i]  
	  else 
	     barph("-"key" unknown.")
      } else {
	   i--;
	   break;
	}
   }
   for(j=i+1;j<=n;j++)  # copy to tmp, what's left on the input
       tmp[j-i]=input[j]
   split("",input,"")   # reset the input args
   for(k in tmp)        #  move the copy back to the input args
	input[k] = tmp[k] 
   n -= i
   return n
 }
  
Discussion
==========

The trick in the above is to clear the options from the command-line such that
the rest of Awk can run right. The final two  for-loops perform that task.

This code is less sophisticated that Robbins' standard _getopt_ function. But
_options_ uses no globals where as _getopt_ drops side-effects into several
places.

